/**
 * Copyright 2018 人人开源 http://www.flow.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.xhtt.modules.app.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.Constant;
import com.xhtt.common.utils.R;
import com.xhtt.modules.app.annotation.Login;
import com.xhtt.modules.app.annotation.LoginUser;
import com.xhtt.modules.sys.controller.AbstractController;
import com.xhtt.modules.sys.entity.SysMenuEntity;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.sys.service.SysMenuService;
import com.xhtt.modules.sys.service.SysRoleMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 系统菜单
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月27日 下午9:58:15
 */
@Api(value = "系统管理-系统菜单", tags = "系统管理-系统菜单")
@RestController
@RequestMapping("app/sys/menu")
public class SysMenuController extends AbstractController {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * web导航菜单
     */
    @ApiOperation("web导航菜单(web)")
    @GetMapping("/nav")
    @Login
    public R nav(@ApiIgnore @LoginUser SysUserEntity user) {
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(user.getUserId());
        Iterator<SysMenuEntity> iterator = menuList.iterator();
        while (iterator.hasNext()) {
            SysMenuEntity se = iterator.next();
            if (se.getMenuType().intValue() == 2) {
                iterator.remove();
            }
        }
        return R.ok().put("menuList", menuList);
    }

    /**
     * web一级导航菜单
     */
    @ApiOperation("web一级导航菜单(web)")
    @GetMapping("/navFirst")
    @Login
    public R navFirst(@ApiIgnore @LoginUser SysUserEntity user) {
        List<SysMenuEntity> menuList = sysMenuService.getUserFirstMenuList(user.getUserId());
        return R.ok().put("menuList", menuList);
    }

    /**
     * web二级+子级导航菜单
     */
    @ApiOperation("web二级+子级导航菜单(web)")
    @GetMapping("/navNext")
    @Login
    public R navNext(@RequestParam Long parentMenuId, @ApiIgnore @LoginUser SysUserEntity user) {
        List<SysMenuEntity> menuList = null;
        Map<Long, List<SysMenuEntity>> m1 = Constant.webMenu.get(user.getUserId());
        if (MapUtils.isNotEmpty(m1)) {
            menuList = m1.get(parentMenuId);
        } else {
            m1 = new HashMap<>();
        }

        if (CollectionUtils.isEmpty(menuList)) {
            menuList = sysMenuService.getUserNextMenuList(parentMenuId, user.getUserId());
            Iterator<SysMenuEntity> iterator = menuList.iterator();
            while (iterator.hasNext()) {
                SysMenuEntity se = iterator.next();
                if (se.getMenuType().intValue() == 2) {
                    iterator.remove();
                }
            }
            m1.put(parentMenuId, menuList);
            Constant.webMenu.put(user.getUserId(), m1);
        }
        SysMenuEntity first = null;
        if (CollectionUtils.isNotEmpty(menuList))//取出狗日的第一个菜单
        {
            first = getFirst(menuList);
        }
        return R.ok().put("menuList", menuList).put("first", first);
    }

    private SysMenuEntity getFirst(List<SysMenuEntity> ms) {
        SysMenuEntity m = ms.get(0);
        if (m.getType().intValue() == 1) {
            return m;
        } else {
            if (CollectionUtils.isNotEmpty(m.getList())) {
                return getFirst((List<SysMenuEntity>) m.getList());
            } else {
                return null;
            }

        }
    }

    /**
     * app导航菜单
     */
    @ApiOperation("app导航菜单(app)")
    @GetMapping("/navForApp")
    @Login
    public R navForApp(@ApiIgnore @LoginUser SysUserEntity user) {
        List<SysMenuEntity> menuList = Constant.appMenu.get(user.getUserId().intValue());
        if (CollectionUtils.isEmpty(menuList)) {
            menuList = sysMenuService.getUserMenuList(user.getUserId());
            Iterator<SysMenuEntity> iterator = menuList.iterator();
            while (iterator.hasNext()) {
                SysMenuEntity se = iterator.next();
                if (se.getMenuType().intValue() == 1) {
                    iterator.remove();
                }
            }
            Constant.appMenu.put(user.getUserId(), menuList);
        }
        return R.ok().put("menuList", menuList);
    }

    /**
     * 根据类型获取菜单列表 1web2app
     */
    @ApiOperation("根据类型获取菜单列表 1web2app(web/app)")
    @GetMapping("/list")
    @Login
    public R list(@RequestParam int type) {
        List<SysMenuEntity> menuList = sysMenuService.list(new QueryWrapper<SysMenuEntity>().eq(SysMenuEntity.MENUTYPE, type));
        for (SysMenuEntity sysMenuEntity : menuList) {
            SysMenuEntity parentMenuEntity = sysMenuService.getById(sysMenuEntity.getParentId());
            if (parentMenuEntity != null) {
                sysMenuEntity.setParentName(parentMenuEntity.getName());
            }
        }

        return R.ok().put(Constant.DATA, menuList);
    }

    /**
     * 根据角色获取菜单id集合
     */
    @ApiOperation("根据角色获取菜单id集合(web/app)")
    @GetMapping("/menuIdsByRole")
    @Login
    public R menuIdsByRole(@RequestParam Long roleId) {
        List<Long> menuIds = sysRoleMenuService.queryMenuIdList(roleId);
        return R.ok().put(Constant.DATA, menuIds);
    }

    /**
     * 根据类型获取所有菜单树 1web2app
     */
    @ApiOperation("根据类型获取所有菜单树 1web2app(web/app)")
    @GetMapping("/tree")
    @Login
    public R tree(@RequestParam int type) {
        List<SysMenuEntity> list = sysMenuService.tree(type);

        return R.ok().put(Constant.DATA, list);
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @ApiOperation("选择菜单(添加、修改菜单)(web)")
    @GetMapping("/select")
    @Login
    public R select() {
        //查询列表数据
        List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("一级菜单");
        root.setParentId(-1L);
        root.setOpen(true);
        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**
     * 菜单信息
     */
    @ApiOperation("菜单信息(web/app)")
    @GetMapping("/info/{menuId}")
    @Login
    public R info(@PathVariable("menuId") Long menuId) {
        SysMenuEntity menu = sysMenuService.getById(menuId);
        return R.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @ApiOperation("保存菜单(web)")
    //@SysLog("保存菜单")
    @PostMapping("/save")
    @Login
    public R save(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);

        sysMenuService.save(menu);

        return R.ok();
    }

    /**
     * 修改
     */
    @ApiOperation("修改菜单")
    //@SysLog("修改菜单")
    @PostMapping("/update")
    @Login
    public R update(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);

        sysMenuService.updateById(menu);

        return R.ok();
    }

    /**
     * 删除
     */
    @ApiOperation("删除菜单")
    //@SysLog("删除菜单")
    @PostMapping("/delete/{menuId}")
    @Login
    public R delete(@PathVariable("menuId") long menuId) {
        if (menuId <= 31) {
            return R.error("系统菜单，不能删除");
        }

        //判断是否有子菜单或按钮
        List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
        if (menuList.size() > 0) {
            return R.error("请先删除子菜单或按钮");
        }

        sysMenuService.delete(menuId);

        return R.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuEntity menu) {
        if (StringUtils.isBlank(menu.getName())) {
            throw new RRException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new RRException("上级菜单不能为空");
        }

        //菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new RRException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (menu.getParentId() != 0) {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new RRException("上级菜单只能为目录类型");
            }
            return;
        }

        //按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new RRException("上级菜单只能为菜单类型");
            }
            return;
        }
    }
}
